/**
* All Rights Reserved , Copyright (C) 2022 , 青岛鼎信通讯股份有限公司
*
* MpmProjectVisitExpertService
* 评分细则专家拜访
*
* 修改纪录
* 2022-11-14 版本：1.0 houyuhang 创建。
* @version 版本：1.0
* @author 作者：houyuhang
* 创建日期：2022-11-14
*/
package com.topscomm.mpm.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.cbo.pojo.CboApprovalNodeEntity;
import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.ICboMessageAppService;
import com.topscomm.cbo.service.ICboMessageSysService;
import com.topscomm.cbo.service.ICboUserService;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.pojo.*;
import com.topscomm.mpm.utils.MessageUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.DatacodeCache;
import com.topscomm.tap.common.SessionUserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.mpm.service.IMpmProjectVisitExpertService;
import com.topscomm.mpm.service.impl.auto.MpmProjectVisitExpertServiceAuto;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.util.PrimaryKeyUtil;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.plaf.basic.BasicCheckBoxMenuItemUI;
import java.util.*;
import java.util.stream.Collectors;

@Service(value = "mpmProjectVisitExpertService")
@Scope(value = "singleton")
public class MpmProjectVisitExpertService extends MpmProjectVisitExpertServiceAuto implements IMpmProjectVisitExpertService {
	@Autowired
	private MpmProjectVisitCommentService mpmProjectVisitCommentservice;
	@Autowired
	private DatacodeCache datacodeCache;
	@Autowired
	private ICboMessageAppService cboMessageAppService;
	@Autowired
	private ICboMessageSysService cboMessageSysService;
	@Autowired
	private MpmProjectService mpmProjectService;
	@Autowired
	private MpmProjectAppointmentService mpmProjectAppointmentService;
	@Autowired
	private MpmProjectTeamService mpmProjectTeamService;
	@Autowired
	private ICboUserService cboUserService;
	@Autowired
	private MpmProjectBidScoreService mpmProjectBidScoreService;
	@Autowired
	private MpmProjectProductInfoService mpmProjectProductInfoService;
	/**
	 * @author: houyuhang
	 * @date: 2022-11-14
	 * @param entity
	 * @throws ServiceException
	 * @description:单号生成
	 * @modify:
	 */
	@Override
	protected void beforeInsert(BasicEntity entity){
		super.beforeInsert(entity);
		if (entity.getId() <= 0) {// 赋值Id和单号
			long[] arrayId = PrimaryKeyUtil.GeneIDs(entity.getTableName(), 1);
			entity.setId(arrayId[0]);
			String docNo = String.valueOf(arrayId[0]);
			docNo = docNo.substring(0, 6) + docNo.substring(9);
			entity.setValue(MpmProjectVisitExpertEntity.FieldDocno, docNo);
		}
	}
	/**
	 * @author: houyuhang
	 * @date: 2022-11-15
	 * @param paraMap
	 * @return
	 * @description:获取评标专家拜访反馈信息
	 * @modify:
	 */
	@Transactional
	public Map<String, Object> queryVisitExpertList(Map<String, Object> paraMap) {
		Map<String, Object> dataMap = new HashMap<>();
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" projectcode = '{0}' and (state = 9 or usercode = '{1}') and bidscoretimes = '{2}' order by state asc,visitdate desc,id asc ",
				paraMap.get("projectcode"), this.getSessionUserBean().getUser().getCode(),ConvertUtil.convertToString(paraMap.get("bidscoretimes")));
		List<Map<String, Object>> visitExpertList = this.queryMapByWhere(sql.toString());
		dataMap.put("visitexpert", visitExpertList);
		for (Map<String, Object> visitExpert : visitExpertList) {
			if ("1".equals(ConvertUtil.convertToString(visitExpert.get("state"))) && !StringUtil.isEmpty(ConvertUtil.convertToString(visitExpert.get("latestphase")))) {
				dataMap.put("approvalid", ConvertUtil.convertToLong(visitExpert.get("id")));
			}
		}
		return dataMap;
	}
	/**
	 * @author: houyuhang
	 * @date: 2022/11/25
	 * @description: 审批完成后推送专家拜访结果
	 * @modify:
	 */
	@Override
	protected void afterApprove(TapEntity billEntity, CboApprovalNodeInsEntity nodeIns, CboApprovalNodeEntity node,
								SessionUserBean sessionUserBean) {
		MpmProjectVisitExpertEntity mpmProjectVisitExpertEntity = (MpmProjectVisitExpertEntity) billEntity;
		if(mpmProjectVisitExpertEntity.getState() == 9) {
			// 推送专家拜访结果app消息
			this.sendVisitExpertMessage(mpmProjectVisitExpertEntity);
		}
		// 同步同一次审批其他单据状态
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" projectcode = '{0}' and state = '1' and usercode = '{1}' and bidscoretimes = '{2}'",
				mpmProjectVisitExpertEntity.getProjectcode(), mpmProjectVisitExpertEntity.getUsercode(),mpmProjectVisitExpertEntity.getBidscoretimes());
		List<MpmProjectVisitExpertEntity> mpmProjectVisitExpertEntities = this.queryByWhere(sql.toString());
		List<BasicEntity> basicEntities = new ArrayList<>();
		for (MpmProjectVisitExpertEntity tempEntity : mpmProjectVisitExpertEntities) {
			tempEntity.setState(mpmProjectVisitExpertEntity.getState());
			tempEntity.setLatestphase(mpmProjectVisitExpertEntity.getLatestphase());
			basicEntities.add(tempEntity);
		}
		this.updateBatch(basicEntities);
		super.afterApprove(billEntity, nodeIns, node, sessionUserBean);
	}
	/**
	 * @author: houyuhang
	 * @date: 2022/11/25
	 * @description: 审批完成后推送专家拜访结果
	 * @modify:
	 */
	@Transactional
	public void sendVisitExpertMessage(MpmProjectVisitExpertEntity mpmProjectVisitExpertEntity) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled = 1 and projectcode = '{0}' ", mpmProjectVisitExpertEntity.getProjectcode());
		MpmProjectEntity mpmProjectEntity = mpmProjectService.queryObjectByWhere(sql.toString());
		if (ObjectUtil.isEmpty(mpmProjectEntity)) {
			return;
		}
		// 封装消息内容
		String projectLevel = datacodeCache.getValueDynamic("MpmProjectLevel", mpmProjectEntity.getProjectlevel(), "code", "name");
		List<Map<String, Object>> appList = new ArrayList<>(), sysList = new ArrayList<>();
		Map<String, Object> appMap = new HashMap<>(), sysMap = new HashMap<>();
		String title = "销售项目专家拜访结果提醒";
		StringBufferProxy content = new StringBufferProxy();
		String dispbidscoretimes = datacodeCache.getValueDynamic("MpmBidScoreTimes", mpmProjectVisitExpertEntity.getBidscoretimes(), "code", "name");
		content.appendSingle("【{0}级项目：{1}】发布{2}专家拜访结果，请登录销售项目管理系统查看。",
				projectLevel, mpmProjectEntity.getProjectname(),dispbidscoretimes);
		// 获取发送人员
		List<String> sendUser = this.queryBidUser(mpmProjectEntity);
		if (CollectionUtil.isEmpty(sendUser)) {
			return;
		}
		String sendUserStr = sendUser.stream().collect(Collectors.joining("','","'", "'"));
		sql.clear();
		sql.appendSingle(" enabled = 1 and code in ({0}) ", sendUserStr);
		List<CboUserEntity> cboUserEntities = cboUserService.queryByWhere(sql.toString());
		Map<String, List<CboUserEntity>> cboUserMap = cboUserEntities.stream().collect(Collectors.groupingBy(CboUserEntity::getCode));
		for (String user : sendUser) {
			// app推送
			appMap = MessageUtil.createMessageAppMap(user, title, content.toString(), mpmProjectEntity.getId(),
					MpmProjectEntity.tableName, 0);
			// 系统消息
			sysMap = MessageUtil.createMessageSysMap(user, CollectionUtil.isEmpty(cboUserMap.get(user)) ? "" : cboUserMap.get(user).get(0).getName(), title, content.toString(),
					mpmProjectEntity.getId(), MpmProjectEntity.tableName);
			// 封装
			appList.add(appMap);
			sysList.add(sysMap);
		}
		// 消息批量插入
		cboMessageAppService.insertList(appList);
		cboMessageSysService.insertList(sysList);
	}
	/**
	 * @author: houyuhang
	 * @date: 2022/11/25
	 * @description: 获取投标部专家拜访结果推送人
	 * @modify:
	 */
	@Transactional
	public List<String> queryBidUser(MpmProjectEntity mpmProjectEntity) {
		List<String> userList = new ArrayList<>();
		String projectlevel = mpmProjectEntity.getProjectlevel();
		// 获取标书制作人
		List<String> teamList = new ArrayList<>();
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled=1 and state = 9 and projectcode ='{0}' order by CREATEON desc", mpmProjectEntity.getProjectcode());
		List<MpmProjectAppointmentEntity> mpmProjectAppointmentEntities = mpmProjectAppointmentService.queryByWhere(sql.toString());
		if (!CollectionUtil.isEmpty(mpmProjectAppointmentEntities)) {
			sql.clear();
			sql.appendSingle(" enabled = 1 and projectcode = '{0}' and grouptype = '1' and duty like '%,2,%' and appointmentid = '{1}' ", mpmProjectEntity.getProjectcode(), mpmProjectAppointmentEntities.get(0).getId());
			List<MpmProjectTeamEntity> mpmProjectTeamEntities = mpmProjectTeamService.queryByWhere(sql.toString());
			if (!CollectionUtil.isEmpty(mpmProjectTeamEntities)) {
				teamList = mpmProjectTeamEntities.stream().map(MpmProjectTeamEntity::getUsercode).collect(Collectors.toList());
			}
		}
		// A级项目增加金毅、史先孟、标书制作人，B级项目增加标书制作人
		if (MpmSystemConst.ProjectLevel.A.equals(projectlevel)) {
			userList.add("0335");
			userList.add("2355");
			userList.addAll(teamList);
		} else if (MpmSystemConst.ProjectLevel.B.equals(projectlevel)) {
			userList.addAll(teamList);
		} else {
			return userList;
		}
		// 获取产品线，根据产品线进行对应人员赋值
		sql.clear();
		sql.appendSingle(" projectid = '" + mpmProjectEntity.getId() + "'");
		List<Map<String, Object>> list = mpmProjectProductInfoService.queryMapByWhere(sql.toString());
		if (!CollectionUtil.isEmpty(list)) {
			String productLineCode = list.stream().filter(item -> !ObjectUtil.isEmpty(item.get("productlinecode"))).map(item -> ConvertUtil.convertToString(item.get("productlinecode"))).collect(Collectors.joining(","));
			if (!StringUtil.isEmpty(productLineCode)) {
				userList.addAll(this.queryUserByProductLine(productLineCode));
			}
		}
		// 对重复人员进行过滤
		return userList.stream().distinct().collect(Collectors.toList());
	}
	/**
	 * @author: houyuhang
	 * @date: 2022/11/25
	 * @description: 根据产品线进行对应人员赋值
	 * @modify:
	 */
	@Transactional
	public List<String> queryUserByProductLine(String productLineCode) {
		List<String> userList = new ArrayList<>();
		for (String code : productLineCode.split(",")) {
			code = "," + code + ",";
			if (MpmSystemConst.BidLine.shi.contains(code)) {
				userList.add("2355");
			} else if (MpmSystemConst.BidLine.guo.contains(code)) {
				userList.add("2023");
			} else if (MpmSystemConst.BidLine.fu.contains(code)) {
				userList.add("5352");
			} else if (MpmSystemConst.BidLine.xu.contains(code)) {
				userList.add("5669");
			}
		}
		return userList;
	}
	/**
	 * @author: houyuhang
	 * @date: 2022/12/02
	 * @description: 保存评标专家拜访反馈
	 * @modify:
	 */
	@Transactional
	public void saveVisitExpert(Map<String, Object> paraMap) {
		List<Map<String, Object>> visitExpertList = (List<Map<String, Object>>) paraMap.get("visitexpert");
		List<Map<String, Object>> mapUpdate = new ArrayList<>();
		for (Map<String, Object> visitExpert : visitExpertList) {
			if (ObjectUtil.isEmpty(visitExpert.get("id"))) {
				MpmProjectVisitExpertEntity mpmProjectVisitExpertEntity = new MpmProjectVisitExpertEntity();
				mpmProjectVisitExpertEntity.convertFromMap(visitExpert);
				this.insert(mpmProjectVisitExpertEntity);
			} else {
				mapUpdate.add(visitExpert);
			}
		}
		this.updateBatchMap(mapUpdate);
	}
	/**
	 * @author: houyuhang
	 * @date: 2022-12-05
	 * @param paraMap
	 * @return
	 * @description:获取评标专家拜访反馈信息审批
	 * @modify:
	 */
	@Transactional
	public Map<String, Object> queryApprovalList(Map<String, Object> paraMap) {
		Map<String, Object> dataMap = new HashMap<>();
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled = 1 and relateid = '{0}' order by visitdate desc, id asc ", paraMap.get("id"));
		List<MpmProjectVisitExpertEntity> mpmProjectVisitExpertEntities = this.queryByWhere(sql.toString());
		if (CollectionUtil.isEmpty(mpmProjectVisitExpertEntities)) {
			throw new ServiceException("获取评标专家拜访反馈信息失败，请联系管理员！");
		}
		String bidscoretimes = mpmProjectVisitExpertEntities.get(0).getBidscoretimes();
		dataMap.put("feedback", mpmProjectVisitExpertEntities);
		sql.clear();
		sql.appendSingle(" enabled = 1 and projectcode = '{0}' ", mpmProjectVisitExpertEntities.get(0).getProjectcode());
		dataMap.put("project", mpmProjectService.queryObjectByWhere(sql.toString()));
		sql.clear();
		if(MpmSystemConst.BidScoreTimes.firstTime.equals(bidscoretimes)){
			sql.appendSingle(" enabled = 1 and projectcode = '{0}' and state = 9 and times = '{1}' ", mpmProjectVisitExpertEntities.get(0).getProjectcode(), MpmSystemConst.BidScoreTimes.firstTime);
			dataMap.put("firstshow", mpmProjectBidScoreService.queryByWhere(sql.toString()).size() > 0);
		} else if(MpmSystemConst.BidScoreTimes.secondTime.equals(bidscoretimes)){
			sql.appendSingle(" enabled = 1 and projectcode = '{0}' and state = 9 and times = '{1}' ", mpmProjectVisitExpertEntities.get(0).getProjectcode(), MpmSystemConst.BidScoreTimes.secondTime);
			dataMap.put("secondshow", mpmProjectBidScoreService.queryByWhere(sql.toString()).size() > 0);
		}
		return dataMap;
	}
	/**
	 * @author: houyuhang
	 * @date: 2022/12/02
	 * @description: 保存评标专家拜访反馈
	 * @modify:
	 */
	@Transactional
	public void saveVisitExpertApproval(Map<String, Object> paraMap) {
		List<Map<String, Object>> visitExpertList = (List<Map<String, Object>>) paraMap.get("visitexpert");
		// 需要变更的反馈字段list
		List<String> fields = new ArrayList<>();
		fields.add("canreal");
		// 遍历需要保存的评标专家拜访反馈，如果存在建议内容，新增建议
		List<Map<String, Object>> mapUpdate = new ArrayList<>();
		List<BasicEntity> commentEntityList = new ArrayList<>();
		for (Map<String, Object> visitExpert : visitExpertList) {
			mapUpdate.add(visitExpert);
			if (!ObjectUtil.isEmpty(this.getCommentEntity(visitExpert))) {
				commentEntityList.add(this.getCommentEntity(visitExpert));
			}
		}
		this.updateFieldsBatchMap(mapUpdate, fields);
		mpmProjectVisitCommentservice.insertBatch(commentEntityList);
	}
	/**
	 * @param map
	 * @throws ServiceException
	 * @author: houyuhang
	 * @date: 2022-12-05
	 * @description: 审批节点如果录入了建议内容，将建议内容存入评论表
	 */
	@Transactional
	protected MpmProjectVisitCommentEntity getCommentEntity(Map<String, Object> map) {
		MpmProjectVisitCommentEntity mpmProjectVisitCommentEntity = new MpmProjectVisitCommentEntity();
		if (!ObjectUtil.isEmpty(map.get("advisecomment"))) {
			mpmProjectVisitCommentEntity.setProjectcode(ConvertUtil.convertToString(map.get("projectcode")));
			mpmProjectVisitCommentEntity.setExpertid(ConvertUtil.convertToLong(map.get("id")));
			mpmProjectVisitCommentEntity.setCommentdetail(ConvertUtil.convertToString(map.get("advisecomment")));
			mpmProjectVisitCommentEntity.setCommentname(this.getSessionUserBean().getUser().getName());
			mpmProjectVisitCommentEntity.setCommentcode(this.getSessionUserBean().getUser().getCode());
		}
		return mpmProjectVisitCommentEntity;
	}
}
